package org.example.slave.packet;

import lombok.Data;
import org.example.slave.util.ByteUtil;

import java.io.ByteArrayOutputStream;

/**
 * @author dingrui
 * @since 2022/2/16
 * @description
 */
@Data
public class RegisterSlaveCommandPacket extends CommandPacket {

    private String reportHost;
    private int reportPort;
    private String reportUser;
    private String reportPasswd;
    private long serverId;

    public RegisterSlaveCommandPacket() {
        super.setCommand((byte) 0x15);
    }

    @Override
    public byte[] toBytes() {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.write(getCommand());
        ByteUtil.writeUnsignedIntLittleEndian(serverId, out);
        out.write((byte) reportHost.getBytes().length);
        ByteUtil.writeFixedLengthBytesFromStart(reportHost.getBytes(), reportHost.getBytes().length, out);
        out.write((byte) reportUser.getBytes().length);
        ByteUtil.writeFixedLengthBytesFromStart(reportUser.getBytes(), reportUser.getBytes().length, out);
        out.write((byte) reportPasswd.getBytes().length);
        ByteUtil.writeFixedLengthBytesFromStart(reportPasswd.getBytes(), reportPasswd.getBytes().length, out);
        ByteUtil.writeUnsignedShortLittleEndian(reportPort, out);
        ByteUtil.writeUnsignedIntLittleEndian(0, out);// Fake
        // rpl_recovery_rank
        ByteUtil.writeUnsignedIntLittleEndian(0, out);// master id
        return out.toByteArray();
    }
}
